﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;

namespace RuoyiQuickLogin.Core
{
#if !NET472
#nullable enable
#endif
    public class RuoyiHttp
    {
        public static ServiceStack.Redis.RedisClient Redis = new ServiceStack.Redis.RedisClient("127.0.0.1", 6379);

        public string BaseUrl { get; set; } = string.Empty;
        public string Uuid { get; set; } = string.Empty;
        public string Code { get; set; } = string.Empty;
        public string Token { get; set; } = string.Empty;

        private CookieContainer _cookie = new CookieContainer();

        public string CodeImgUrl => $"{BaseUrl}/captchaImage";
        public string LoginUrl => $"{BaseUrl}/login";

        public RuoyiHttp()
        {

        }

        public bool CodeImg
        {
            get {
                var headers = new Dictionary<string, string>()
                    {
                        { "isToken", "false" }
                    };
                var result = HttpUtils.HttpGet(CodeImgUrl, string.Empty, headers);
                if (result == null) return false;
                JObject jObject = JsonConvert.DeserializeObject<JObject>(result);
                var imgStr = jObject.GetValue("img").ToString();
                Uuid = jObject.GetValue("uuid").ToString();

                Code = Redis.Get<string>("captcha_codes:" + Uuid);

                using (var stream = new MemoryStream(Convert.FromBase64String(imgStr)))
                {
                    return true;//Image.FromStream(stream);
                } 
            }
        }

        public void Login(string username, string password)
        {
            var ok = CodeImg;
            if (!ok) return;
            var headers = new Dictionary<string, string>()
                {
                    { "isToken", "false" }
                };
            var body = $"{{\"username\":\"{username}\",\"password\":\"{password}\",\"code\":\"{Code}\",\"uuid\":\"{Uuid}\"}}";
            var result = HttpUtils.HttpRestPost(ref _cookie, LoginUrl, headers, body);
            if (result == null) return;
            JObject jObject = JsonConvert.DeserializeObject<JObject>(result);
            Token = "Bearer " + jObject.GetValue("token").ToString();
        }
    }
}
